package com.cxb.carrecorder;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class PlayerActivity extends Activity implements SurfaceHolder.Callback {

	private String dirPath = null;
	private String videoPath = null;
	private List<File> fileList = null;
	private MediaPlayer mMediaPlayer = null;
	private SurfaceHolder mSurfaceHolder = null;

	private Handler handler = null;
	private SeekBar seekBar = null;
	private ImageButton playButton = null;
	private String szPath = null;// LOG�ļ�����·��
	private FrameLayout videoCtrl = null;
	private Runnable updateThread = null;
	private int index;

	private TextView mPlayTime = null;
	private TextView mTotalTime = null;
	private ImageButton mDeleteButton = null;
	private ImageButton mLockButton = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.player_activity);

		if (CarRecorderDebug.DEBUG)
			szPath = Environment.getExternalStorageDirectory() + "/log.txt";

		Intent intent = getIntent();

		dirPath = intent.getStringExtra("dir_path").toString() + File.separator;
		videoPath = intent.getStringExtra("path").toString();
		File videoDir = new File(dirPath);
		if (videoDir.exists()) {
			fileList = getVideoFiles(videoDir);

		}

		index = getVideoIndex(videoPath);
		SurfaceView mSurfaceView = (SurfaceView) findViewById(R.id.video_surface);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setFixedSize(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		videoCtrl = (FrameLayout) findViewById(R.id.video_ctrl);
		mSurfaceView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (videoCtrl.getVisibility() != View.VISIBLE)
					videoCtrl.setVisibility(View.VISIBLE);
				else
					videoCtrl.setVisibility(View.GONE);
			}
		});

		playButton = (ImageButton) findViewById(R.id.play_button);
		playButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!isValidFile(fileList.get(index)))
				{
					Toast.makeText(PlayerActivity.this,
							getString(R.string.file_exists), Toast.LENGTH_SHORT)
							.show();
					return;
				}
				if (mMediaPlayer != null) {
					if (mMediaPlayer.isPlaying()) {
						mMediaPlayer.pause();
						playButton.setImageResource(R.drawable.start_button);
					} else {
						mMediaPlayer.start();
						playButton.setImageResource(R.drawable.stop_button);
//						handler.post(updateThread);
					}
				}
			}
		});

		ImageButton nextButton = (ImageButton) findViewById(R.id.video_next_button);
		nextButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (index < fileList.size() - 1) {
					if(!isValidFile(fileList.get(index + 1)))
					{
						index ++;
						Toast.makeText(PlayerActivity.this,
								getString(R.string.file_exists), Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (mMediaPlayer != null) {

						mMediaPlayer.stop();
						mMediaPlayer.release();

					}
					playVideo(fileList.get(++index).getAbsolutePath());
				} else {
					Toast.makeText(PlayerActivity.this,
							getString(R.string.lastnofity), Toast.LENGTH_SHORT)
							.show();
				}
			}
		});

		ImageButton prevButton = (ImageButton) findViewById(R.id.video_pre_button);
		prevButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (index > 0) {
					if(!isValidFile(fileList.get(index - 1)))
					{
						index --;
						Toast.makeText(PlayerActivity.this,
								getString(R.string.file_exists), Toast.LENGTH_SHORT)
								.show();
						return;
					}
					if (mMediaPlayer != null) {
						mMediaPlayer.stop();
						mMediaPlayer.release();
					}
					playVideo(fileList.get(--index).getAbsolutePath());
				} else {
					Toast.makeText(PlayerActivity.this,
							getString(R.string.firstnofity), Toast.LENGTH_SHORT)
							.show();
				}
			}

		});

		ImageButton returnButton = (ImageButton) findViewById(R.id.back_button);
		returnButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					mMediaPlayer.release();
					mMediaPlayer = null;
				}
				handler.removeCallbacks(updateThread);
				finish();
			}
		});

		mPlayTime = (TextView) findViewById(R.id.play_time);
		mTotalTime = (TextView) findViewById(R.id.total_time);

		mDeleteButton = (ImageButton) findViewById(R.id.delete_button);
		mDeleteButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					mMediaPlayer.release();
					mMediaPlayer = null;
				}

				File file = new File(fileList.get(index).getAbsolutePath());
				file.delete();
				handler.removeCallbacks(updateThread); 
				finish();
			}
		});

		mLockButton = (ImageButton) findViewById(R.id.lock_button);
		mLockButton.setOnClickListener(new ImageButton.OnClickListener() {
			@Override
			public void onClick(View v) {
				String strFile = fileList.get(index).getAbsolutePath();
				String strNewFile = null;
				String strLockDir = VideoRecorder.VIDEOS_PATH_LOCKED;
				if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					mMediaPlayer.release();
					mMediaPlayer = null;
				}
				if(isLockFile(strFile))
				{
					strNewFile = strFile.replace(VideoRecorder.VIDEOS_PATH_LOCKED, VideoRecorder.VIDEOS_PATH_NORMAL);
					mLockButton.setImageResource(R.drawable.open_lock_button);
				}
				else
				{
					strNewFile = strFile.replace(VideoRecorder.VIDEOS_PATH_NORMAL, VideoRecorder.VIDEOS_PATH_LOCKED);
					mLockButton.setImageResource(R.drawable.lock_file_button);
				}
				File newFile = new File(strNewFile);  
				File srcFile = new File(strFile);
				File lockDirFile = new File(strLockDir);  
				if (!lockDirFile.exists()){
					lockDirFile.mkdirs();  
				}

				srcFile.renameTo(newFile);  
				
				fileList.set(index, newFile);
				File f = fileList.get(index);
				playVideo(strNewFile);
			}
		});
		
		updateLock();
		
		handler = new Handler();
		updateThread = new Runnable() {
			@Override
			public void run() {
				if(mMediaPlayer != null)
				{
					updatePlayUI();
				}
				handler.postDelayed(updateThread, 1000);
			}
		};
	};

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	private List<File> getVideoFiles(File file) {

		List<File> addFiles = new ArrayList<File>();

		File[] VideoFiles = file.listFiles();

		if (VideoFiles != null) {
			for (File norFile : VideoFiles) {
				if (norFile.getName().endsWith("3gp")) {
					addFiles.add(norFile);
				}
			}
		}

		Collections.sort(addFiles, new Comparator<File>() {

			@Override
			public int compare(File lhs, File rhs) {
				if (lhs.lastModified() > rhs.lastModified()) {
					return -1;
				} else if (lhs.lastModified() < rhs.lastModified()) {
					return 1;
				}
				return 0;
			}
		});

		return addFiles;
	}

	private void playVideo(String videoPath) {
		if(mMediaPlayer != null)
		{
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mMediaPlayer.setDisplay(mSurfaceHolder);
		
		mMediaPlayer
		.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer arg0) {
				playButton.setImageResource(R.drawable.start_button);
				if(mMediaPlayer != null)
				{
					mPlayTime.setText(String.format("%02d:%02d", 0, 0));
					seekBar.setProgress(0);
					mMediaPlayer.seekTo(0);
				}
			}
		});
		updateLock();
		System.gc();
		try {
			mMediaPlayer.setDataSource(videoPath);
		} catch (Exception e) {
			CarRecorderDebug.printf(e.toString(), szPath);
		}

		try {
			mMediaPlayer.prepare();
		} catch (Exception e) {
			CarRecorderDebug.printf(e.toString(), szPath);
		}

		mMediaPlayer.start();

		seekBar = (SeekBar) findViewById(R.id.seekbar);
		seekBar.setMax(mMediaPlayer.getDuration());
		seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (fromUser && mMediaPlayer != null) {
					mMediaPlayer.seekTo(progress);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

		});

		handler.post(updateThread);
		
		if (mMediaPlayer.isPlaying())
			playButton.setImageResource(R.drawable.stop_button);
		else
			playButton.setImageResource(R.drawable.start_button);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (index >= fileList.size()) {
			index = fileList.size() - 1;
		}
		playVideo(fileList.get(index).getAbsolutePath());
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	}

	public int getVideoIndex(String path) {

		for (int i = 0; i < fileList.size(); i++) {
			String currentPath = fileList.get(i).getAbsolutePath();
			if (currentPath.equals(path)) {
				return i;
			}
		}
		return 0;
	}

	private void updateLock()
	{
		if(isLockFile(fileList.get(index).getAbsolutePath()))
			mLockButton.setImageResource(R.drawable.lock_file_button);
		else
			mLockButton.setImageResource(R.drawable.open_lock_button);
	}
	private void updatePlayUI()
	{
		if(mMediaPlayer != null && mMediaPlayer.isPlaying())
		{
			long times = mMediaPlayer.getDuration() / 1000;
			String strTime = String.format("%02d:%02d", times / 60, times % 60);
			mTotalTime.setText(strTime);
			times = mMediaPlayer.getCurrentPosition() / 1000;
			strTime = String.format("%02d:%02d", times / 60, times % 60);
			mPlayTime.setText(strTime);
			seekBar.setProgress(mMediaPlayer.getCurrentPosition());
		}
	}
	
	private boolean isLockFile(String strFile)
	{
		return strFile.contains(VideoRecorder.VIDEOS_PATH_LOCKED);
	}
	
	private boolean isValidFile(File file)
	{
		return file.exists();
	}
}
